let teamNames = ['青云组', '风云组', '玲珑组', '逍遥组', '开金组', '技术开发组'];//业务小组列表

let targetSheetMap = {
    '迭代统计': '迭代产能'
};
main();

//* 主函数
function main() {
    let targetRowData = getTargetRecord(Context.argv.sheetId, Context.argv.id);
    //* [测试代码]-start 
    // let targetRowData = { '迭代列表': ['202410-2'], '类型': '迭代统计', '数据表名称': '2024迭代需求' };
    //* [测试代码]-end
    let interationList = targetRowData['迭代列表'];
    let sheetName = targetRowData['数据表名称'];
    let analysisType = targetRowData['类型'];
    let targetSheet = getSheetByName(targetSheetMap[analysisType]);
    if (targetSheet) {
        let updateRecords = [];
        let interationSheet = getSheetByName(sheetName);
        loop(interationList, (interation) => {
            loop(teamNames, (teamName) => {
                let { workDays, estimateWorkDays } = summaryWorkDays(interationSheet.id, teamName, interation);
                let v = updateSummary(targetSheet.id, interation, teamName, workDays, estimateWorkDays);
                if (v) updateRecords.push(v);
            })
        })
        if (updateRecords.length > 0) {
            Application.Record.UpdateRecords({
                SheetId: targetSheet.id,
                Records: updateRecords,
            })
        }
    }
}
//* 汇总各组开发人天
function summaryWorkDays(sheetId, teamName, interation) {
    let records = getSheetData(sheetId);
    let workDays = 0;
    let estimateWorkDays = 0;
    loop(records, (record) => {
        let fields = record.fields;
        let sheetInteration = fields['迭代'];
        let isParent = fields['是否是父任务'] == '1';
        if (sheetInteration == interation) {
            let tags = fields['需求标签'] || [];
            let shouldIgnored = tags.includes('工时异常') || tags.includes('异常需求') || tags.includes('需求已移除') || isParent;//过滤掉异常数据
            let realTaskWorkDays = fields['实际总人天校准'] || 0;
            let estimateTaskWorkDays = fields['架构组预估人天'] || 0;
            if (!shouldIgnored) {
                if (teamName == '开金组') {
                    //* 开金组和火舞组在组织架构上属于同一开发团队
                    if (['开金组', '火舞组'].includes(fields['负责小组'])) {
                        workDays += realTaskWorkDays;
                        estimateWorkDays += estimateTaskWorkDays;
                    }
                } else {
                    if (fields['负责小组'] == teamName) {
                        workDays += realTaskWorkDays;
                        estimateWorkDays += estimateTaskWorkDays;
                    }
                }
            }
        }
    })
    return { workDays, estimateWorkDays };
}
//* 更新到迭代产能数据中（按小组维度）
function updateSummary(sheetId, iterationVersion, teamName, days, estimateWorkDays) {
    let recordInst = Application.Record.GetRecords({ SheetId: sheetId });
    let records = recordInst.records;
    let matchedRecord;
    for (let i = 0; i < records.length; i++) {
        let record = records[i];
        let fields = record.fields;
        if (fields['业务小组'] == teamName && fields['迭代'] == iterationVersion) {
            matchedRecord = record;
            break;
        }
    }
    if (matchedRecord) {
        return {
            id: matchedRecord.id,
            fields: {
                '总人天': days,
                '架构组评估人天': estimateWorkDays,
            }
        }
    }
}
/* 以下为通用方法,最新代码在lib目录下;受限于wps脚本运行的环境无法使用引用脚本,所以需要手动去更新以下脚本 */
function getTargetRecord(sheetId, recordId) {
    let result = Application.Record.GetRecord({ SheetId: sheetId, RecordId: recordId });
    return result.fields;
}


// 获取sheet中的数据
function getSheetData(sheetId) {
    let all = [];
    let offSet = null;
    while (all.length === 0 || offSet) {
        let recordInstance = Application.Record.GetRecords({ SheetId: sheetId, Offset: offSet });
        offSet = recordInstance.offset;
        all = all.concat(recordInstance.records);
    }
    return all;
}

// 根据数据表名，查找表对象
function getSheetByName(name) {
    let sheets = Application.Sheet.GetSheets();
    let matchedSheet;
    for (let i = 0; i < sheets.length; i++) {
        if (sheets[i].name === name) {
            matchedSheet = sheets[i];
            break;
        }
    }
    if (!matchedSheet) console.warn('The specified table not existed!')
    return matchedSheet;
}
function loop(list, cb) {
    for (let i = 0; i < list.length; i++) {
        cb(list[i], i);
    }
}